package me.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 你好世界的测试Controller
 *
 * @author Rainh
 */

@Controller
public class HelloServlet {

    @RequestMapping(path="/hello")
    public String sayHello(){

        System.out.println("Hello,SpringMvc");
        return "success";
    }

    /**
     * 传统的方式上传文件
     *   tradition：传统
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadController")
    public String uploadControllerByTradition(HttpServletRequest request) throws Exception {

        //获取上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断该位置是否存在
        File file = new File(path);
        if(!file.exists()){
            //如果文件不存在,创建该文件夹
            file.mkdirs();
        }
        //解析request对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解析request
        List<FileItem> items = upload.parseRequest(request);
        //遍历循环
        for (FileItem item : items) {
            //判断是否是一个上传文件选项
            if(item.isFormField()){
                //是普通表单
            }else {
                //是文件上传
                //获取文件名称
                String name = item.getName();
                //将文件设置为唯一值
                String replace = UUID.randomUUID().toString().replace("-", "");

                //完成文件上传
                item.write(new File(path,replace+"_"+name));
                //删除临时文件
                item.delete();
            }
        }
        return "success";
    }

    /**
     * springMvc方式文件上传
     * @return
     */
    @RequestMapping(value = "/uploadController2")
    public String uploadControllerBySpringMvc(HttpServletRequest request,MultipartFile upload) throws IOException {
        //获取上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断该位置是否存在
        File file = new File(path);
        if(!file.exists()){
            //如果文件不存在,创建该文件夹
            file.mkdirs();
        }
        //获取文件名
        String filename = upload.getOriginalFilename();
        //配置唯一名
        String replace = UUID.randomUUID().toString().replace("-", "");
        String name = replace+"_"+filename;
        //完成文件上传
        upload.transferTo(new File(path,name));

        return "success";
    }
}
